package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Objects;

/**
 * UserServiceImpl
 *
 * @author liliudong
 * @version 1.0
 * @description 用户
 * @date 2023/6/25 11:53
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final WeChatProperties weChatProperties;

    private final UserMapper userMapper;

    private final static String LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Override
    public User login(String code) {
        String openid = loginByCode(code);
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        User user = userMapper.selectByOpenid(openid);
        if (Objects.isNull(user)) {
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }
        return user;
    }

    private String loginByCode(String code) {
        HashMap<String, String> requestParam = new HashMap<>(8);
        requestParam.put("appid", weChatProperties.getAppid());
        requestParam.put("secret", weChatProperties.getSecret());
        requestParam.put("js_code", code);
        requestParam.put("grant_type", "authorization_code");
        String responseStr = HttpClientUtil.doGet(LOGIN_URL, requestParam);
        JSONObject responseObject = JSON.parseObject(responseStr);
        return responseObject.getString("openid");
    }
}
